package com.wxn.learncompose

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Address
import android.location.Criteria
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.view.WindowCompat
import com.wxn.learncompose.pagers.AnimPager
import com.wxn.learncompose.pagers.AnimPager2
import com.wxn.learncompose.pagers.AnimPager3
import com.wxn.learncompose.pagers.AnimPager4
import com.wxn.learncompose.pagers.CartPager
import com.wxn.learncompose.pagers.ClickableTextPager
import com.wxn.learncompose.pagers.ColumnCardPager
import com.wxn.learncompose.pagers.FlowLayoutCardPager
import com.wxn.learncompose.pagers.GustureAnimPager
import com.wxn.learncompose.pagers.HorizontalPagerPager
import com.wxn.learncompose.pagers.ModelBottomSheetLayoutCardPager
import com.wxn.learncompose.pagers.MyBottomNavigateBar
import com.wxn.learncompose.pagers.RowCardPager
import com.wxn.learncompose.pagers.ScaffoldCardPager
import com.wxn.learncompose.pagers.ScaffoldCardPager2
import com.wxn.learncompose.pagers.SliderPager
import com.wxn.learncompose.pagers.SurfaceCardPager
import com.wxn.learncompose.pagers.SvgaImagePager
import com.wxn.learncompose.pagers.TextClickPager
import com.wxn.learncompose.ui.theme.LearnComposeTheme
import java.util.Locale

class MainActivity : ComponentActivity() {
    
    val TAG = "MainActivity"
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false)

//        getLocation()
        setContent {
            LearnComposeTheme {
                // A surface container using the 'background' color from the theme
//                MainPager()
//                AlertDialogPager()
//                ButtonsPager()
//                CardPager()
//                FAB_Icon_IconButton()
//                ImagePager()
//                SvgaImagePager()
//                SliderPager()
//                ClickableTextPager()
//                RowCardPager()
//                ColumnCardPager()
//                FlowLayoutCardPager()
//                ScaffoldCardPager()
//                SurfaceCardPager()
//                ScaffoldCardPager2()
//                ModelBottomSheetLayoutCardPager()
//                HorizontalPagerPager()
//                AnimPager()
//                AnimPager2()
//                AnimPager3()
//                AnimPager4()
//                GustureAnimPager()
//                TextClickPager()
                CartPager()
            }
        }

    }


    val LOCATION_CODE = 301;
    private var locationManager:LocationManager? = null

    @SuppressLint("MissingPermission")
    fun getProvider():String?{
        //1.获取位置管理器
        locationManager=  getSystemService( LOCATION_SERVICE) as? LocationManager?

        //2.获取位置提供器，GPS或是NetWork
        val  providers : MutableList<String>? = locationManager?.getProviders(true)

        return if (providers?.contains(LocationManager.GPS_PROVIDER) == true) {
            //如果是GPS
            Log.v(TAG, "定位方式GPS");
            LocationManager.GPS_PROVIDER;
        } else if (providers?.contains(LocationManager.NETWORK_PROVIDER) == true) {
            //如果是Network
            Log.v(TAG, "定位方式Network");
            LocationManager.NETWORK_PROVIDER;
        }else {

            val criteria =  Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            criteria.setAltitudeRequired(false);//不要求海拔
            criteria.setBearingRequired(false);//不要求方位
            criteria.setCostAllowed(true);//允许有花费
            criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
            val provider:String? = locationManager?.getBestProvider(criteria, true) //定位的provider
            val location : Location?  = provider?.let { locationManager?.getLastKnownLocation(it) }
            if (location != null) {
                //不为空,显示地理位置经纬度
                val longitude = "Longitude:" + location.getLongitude();
                val latitude = "Latitude:" + location.getLatitude();
            }

            if (provider.isNullOrEmpty()) {
                Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
                null
            }else {
                provider
            }
        }
//        if (locationProvider == null || providers.isNullOrEmpty()) {
//            return null
//        }
    }

    fun getLocation(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
                //请求权限
                ActivityCompat.requestPermissions(this,
                    arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION), LOCATION_CODE);
            } else {
                val locationProvider = getProvider() ?: return
                //3.获取上次的位置，一般第一次运行，此值为null
                val location: Location? = locationManager?.getLastKnownLocation(locationProvider);
                if (location!=null){
                    Toast.makeText(this, location.longitude.toString() + " " +
                            location.latitude + "",Toast.LENGTH_SHORT).show();
                    Log.v(TAG, "获取上次的位置-经纬度："+location.longitude +"   "+location.latitude);
                    getAddress(location);
                }else{
                    //监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
                    locationManager?.requestLocationUpdates(locationProvider, 3000, 1f,locationListener);
                }
            }
        } else {
            val locationProvider = getProvider() ?: return
            val  location :Location?= locationManager?.getLastKnownLocation(locationProvider);
            if (location!=null){
                Toast.makeText(this, location.longitude.toString() + " " +
                        location.latitude + "", Toast.LENGTH_SHORT).show();
                Log.v(TAG, "获取上次的位置-经纬度："+location.longitude +"   "+location.latitude);
                getAddress(location);
            }else{
                //监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
                locationManager?.requestLocationUpdates(locationProvider, 3000, 1f,locationListener);
            }
        }
    }

    val locationListener : LocationListener = object : LocationListener {
        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        override public fun onStatusChanged( provider:String,  status:Int,  extras:Bundle) {}
        // Provider被enable时触发此函数，比如GPS被打开
        override fun onProviderEnabled( provider:String) {}
        // Provider被disable时触发此函数，比如GPS被关闭
        override
        public fun onProviderDisabled( provider:String) {}
        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        override public fun onLocationChanged( location:Location) {
            if (location != null) {
                //如果位置发生变化，重新显示地理位置经纬度
                Toast.makeText(MyApp.context(), location.longitude.toString() +  " " +
                        location.latitude + "", Toast.LENGTH_SHORT).show()
                Log.v(TAG, "监视地理位置变化-经纬度："+location.longitude +"   "+location.latitude);
                getAddress(location);
            }
        }
    }

    /***
     * 需要权限
     */
    @SuppressLint("MissingPermission")
    @Override
    public fun onRequestPermissionsResult( requestCode:Int,  permissions:Array<String>,  grantResults:Array<Int>) {
        when (requestCode) {
            LOCATION_CODE ->
            if(grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "申请权限", Toast.LENGTH_LONG).show();
                try {
                    val providers :List<String>?= locationManager?.getProviders(true);
                    val locationProvider = if (providers?.contains(LocationManager.NETWORK_PROVIDER) == true) {
                        //如果是Network
                        LocationManager.NETWORK_PROVIDER;
                    }else if (providers?.contains(LocationManager.GPS_PROVIDER) == true) {
                        //如果是GPS
                        LocationManager.GPS_PROVIDER;
                    } else {""}
                    val location:Location? = locationManager?.getLastKnownLocation(locationProvider);
                    if (location!=null){
                        Toast.makeText(this, location.longitude.toString() + " " +
                                location.latitude + "", Toast.LENGTH_SHORT).show();
                        Log.v(TAG, "获取上次的位置-经纬度："+location.getLongitude()+"   "+location.getLatitude());
                    }else{
                        // 监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
                        locationManager?.requestLocationUpdates(locationProvider, 0, 0f,locationListener);
                    }

                }catch (e: SecurityException){
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(this, "缺少权限", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }


    //获取地址信息:城市、街道等信息
    private fun  getAddress( location:Location):List<Address>? {
        var result:List<Address>? = null;
        try {
            if (location != null) {
                var gc : Geocoder =  Geocoder(this, Locale.getDefault());
                result = gc.getFromLocation(location.getLatitude(),
                    location.getLongitude(), 1);
                Toast.makeText(this, "获取地址信息："+result.toString(), Toast.LENGTH_LONG).show();
                Log.v(TAG, "获取地址信息："+result.toString());
//                获取地址信息：[Address[addressLines=[0:"湖北省武汉市洪山区三泰街",1:"奥山光谷世纪城",2:"全友家居(高新大道店)",3:"百利高生活超市(奥山光谷世纪城店)",4:"桔子酒店(武汉光谷科技会展中心店)",5:"A4栋",6:"龙湖新壹城",7:"美橙酒店(武汉光谷科技会展中心店)",8:"存在花意(龙湖新壹城店)",9:"中国十五冶金建设集团有限公司",10:"朝曦运动游园"],feature=null,admin=湖北省,sub-admin=null,locality=武汉市,thoroughfare=三泰街,postalCode=null,countryCode=CN,countryName=中国,hasLatitude=true,latitude=30.492126598456693,hasLongitude=true,longitude=114.51552974492287,phone=null,url=null,extras=null]]
            }
        } catch (e: Exception ) {
            e.printStackTrace();
        }
        return result;
    }

    override fun onDestroy() {
        super.onDestroy();
        locationManager?.removeUpdates(locationListener);
    }
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    LearnComposeTheme {
//        MainPager()
//        AlertDialogPager()
//        ButtonsPager()
//        CardPager()
//        FAB_Icon_IconButton()
//        ImagePager()
//        SvgaImagePager()
//        SliderPager()
//        ClickableTextPager()
//        RowCardPager()
//        ColumnCardPager()
//        FlowLayoutCardPager()
//        ScaffoldCardPager()
//        SurfaceCardPager()
//        ScaffoldCardPager2()
//        ModelBottomSheetLayoutCardPager()
//        HorizontalPagerPager()
//        AnimPager()
//        AnimPager2()
//        AnimPager3()
//        AnimPager4()
//        GustureAnimPager()
//        TextClickPager()
        CartPager()
    }


}